<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  v-show="showSearch" label-width="68px">

        <!-- <el-form-item label="机构" prop="deptId">
          <treeselect v-model="queryParams.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择机构" style="width:300px;"/>
        </el-form-item> -->
        <el-form-item label="机构名称" prop="subBankName">
          <el-input
            v-model="queryParams.subBankName"
            placeholder="请输入分行/支行名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['server:config:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['server:config:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['server:config:remove']"
          >删除</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['server:config:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="分行号" align="center" prop="subBankCode" /> -->
        <el-table-column label="机构名称" align="center" prop="subBankName" :show-overflow-tooltip="true" />
        <el-table-column label="服务器IP" align="center" prop="serverIp" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态" width="200">
            <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
            </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['server:config:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['server:config:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="450px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <!-- <el-form-item label="分行号" prop="subBankCode">
            <el-input v-model="form.subBankCode" placeholder="请选择分行号" suffix-icon="el-icon-caret-right" :readonly="true" @click.native="getBranchInfo"/>
          </el-form-item> -->
          <el-form-item label="行号" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="选择网点" />
          </el-form-item>
          <!-- <el-form-item label="分行名称" prop="subBankName">
            <el-input v-model="form.subBankName" placeholder="请输入分行名" :disabled="true"/>
          </el-form-item> -->
          <el-form-item label="服务器IP" prop="serverIp">
            <el-input v-model="form.serverIp" placeholder="请输入服务器IP" />
          </el-form-item>
          <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
        </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


    <el-dialog :visible.sync="showDialog" width="600px" title="银行编码" append-to-body>
      <el-table :data="listData" @row-click="handleSelect" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column prop="deptName" label="分行名称" />
        <el-table-column prop="deptCode" label="分行号" />
      </el-table>
    </el-dialog>
    </div>
  </template>

<style lang="scss" scoped>
.app-container {
  ::v-deep.vue-treeselect__placeholder {
    font-size: 13px;
  }
  ::v-deep.vue-treeselect__control {
    height: 30px;
  }
}
</style>

  <script>
  import { getConfig, delConfig, addConfig, updateConfig, refreshCache } from "@/api/system/config";
  import { listServerConfig, addServerConfig, delServerConfig,getServerConfig,updateServerConfig} from "@/api/iis/subbankserver";
  import { listDept } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Config",
    dicts: ['sys_yes_no', 'sys_normal_disable'],
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 参数表格数据
        configList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          subBankCode: undefined,
          serverIp: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          subBankCode: [
            { required: true, message: "行号不能为空", trigger: "blur" }
          ],
          serverIp: [
          { required: true, validator: this.validateIP, trigger: 'blur' }
          ]
        },
        showDialog: false,  // 控制弹窗显示
        listData: [],
        deptqueryParams: {
          deptCode: undefined,
          deptLevel: '2'
        },
        deptOptions: []
      };
    },
    created() {
      this.getList();
      listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    methods: {
      /** 查询参数列表 */
      getList() {
        this.loading = true;
        listServerConfig(this.queryParams).then(response => {
            this.configList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
            subBankCode: undefined,
            subBankName: undefined,
            serverIp: undefined,
            status: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加服务器配置";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.serverId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const serverId = row.serverId || this.ids
        console.log("serveId", serverId);
        getServerConfig(serverId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改服务器配置";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.serverId != undefined) {
              updateServerConfig(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addServerConfig(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const configIds = row.serverId || this.ids;
        this.$modal.confirm('是否确认删除参数编号为"' + configIds + '"的数据项？').then(function() {
            return delServerConfig(configIds);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('server/config/export', {
          ...this.queryParams
        }, `config_${new Date().getTime()}.xlsx`)
      },
      /** 刷新缓存按钮操作 */
      handleRefreshCache() {
        refreshCache().then(() => {
          this.$modal.msgSuccess("刷新成功");
        });
      },
      handleSelect(row) {
        this.$refs.form.clearValidate(['subBankCode']);
        this.form.subBankCode = row.deptCode;
        this.form.subBankName = row.deptName;
        this.form.deptId = row.deptId;
        this.showDialog = false;
      //this.$forceUpdate();
      },
      handleCurrentChange(currentRow) {
        this.selectedRow = currentRow;
      },
      getBranchInfo() {
        listDept(this.deptqueryParams).then(response => {
            console.log(response.data);
            this.listData = response.data;
        });
        this.showDialog = true;
      },
      validateIP(rule, value, callback) {
        const ipReg = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
        if (!value) {
          callback(new Error('IP 地址不能为空'));
        } else if (!ipReg.test(value)) {
          callback(new Error('请输入合法的 IPv4 地址'));
        } else {
          callback();
        }
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
    },
  };
  </script>
